package com.wufan.day02;

/**
 * 查找
 * @author SongWufan
 * @date 2021/3/5 15:54
 */
public class ArraySearchTest {
    public static void main(String[] args) {
        String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"};
        //线性查找
        String target = "B";
        //标识
        boolean isFlag = true;
        for (int i = 0; i < arr.length; i++){
            if (target.equals(arr[i])){
                System.out.println("已找到指定元素，位置为第"+(i+1));
                isFlag = false;
                break;
            }
        }
        if (isFlag){
            System.out.println("未找到");
        }
        /**
         * 二分查找
         */
        int[] arr2 = new int[]{-98,-34,2,34,54,66,79,105,210,333};

        int target2 = -34;
        //初始的首索引
        int head = 0;
        //初始的末索引
        boolean isFlag1 = true;
        int end = arr2.length - 1;

        while (head <= end){
            int middle = (head + end) / 2;
            if (target2 == arr2[middle]){
                System.out.println("位置为"+(middle+1));
                isFlag1 = false;
                break;
            }
            else if (arr2[middle] > target2){
                end = middle - 1;
            }
            else{
                head = middle + 1;
            }
        }
        if (isFlag1){
            System.out.println("未找到");
        }
    }
}
